package com.kerraway.model;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.IdentityGenerator;

import java.io.Serializable;

/**
 * @author tw
 * @date 2018/10/26
 * 用于创建数据时优先使用指定id，否则使用数据库自增id
 */
public class IdCustomGenerator extends IdentityGenerator {

  @Override
  public Serializable generate(SessionImplementor sessionImplementor, Object object) throws HibernateException {
    Serializable id = sessionImplementor.getEntityPersister(null, object)
        .getClassMetadata().getIdentifier(object, sessionImplementor);
    return id != null ? id : super.generate(sessionImplementor, object);
  }

}